﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using MineBoxRelease.Core;
using MineBoxRelease.Core.View;
using MineBoxRelease.Model;
using ListViewItem = System.Windows.Controls.ListViewItem;
using RadioButton = System.Windows.Controls.RadioButton;

namespace MineBoxRelease.View
{
    /// <summary>
    /// MusicBox.xaml 的交互逻辑
    /// </summary>
    public partial class MusicBoxView : BaseView
    {
        enum PlayerState
        {
            Stoped, Paused, Playing
        }
        enum LoopMode
        {
            SingleCycle, ListCycle, Random
        }
        private MediaPlayer player;
        private DispatcherTimer timer;
        private PlayerState state;
        private LoopMode mode;
        private ObservableCollection<Music> musicList;

        public ObservableCollection<Music> MusicList
        {
            set
            {
                musicList = value;
                lvMusic.ItemsSource = MusicList;
            }
            get { return musicList; }
        }

        public MusicBoxView(string title = null)
        {
            InitializeComponent();
            InitializeData();
            InitializeEvent();
            Title = title;
            if (title != null)
                tbTitle.Text = title;
        }
        //初始化变量
        private void InitializeData()
        {
            state = PlayerState.Stoped;
            mode = LoopMode.ListCycle;
            MusicList = new ObservableCollection<Music>();
        }

        //初始化事件
        private void InitializeEvent()
        {
            btnImport.Click += btnImport_Click;
            btnPlay.Click += btnPlay_Click;
            btnNext.Click += (s, e) => Next(true);
            btnPrevious.Click += (s, e) => Play(lvMusic.SelectedIndex - 1);
        }

        //导入音乐
        void btnImport_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "音乐文件(*.mp3)|*.mp3";
            dialog.DereferenceLinks = false;
            dialog.Multiselect = true;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                foreach (string str in dialog.FileNames)
                {
                    Music music = MusicHelper.MusicFromFile(str);
                    if (music != null)
                        MusicList.Add(music);
                }
            }
            ViewManager.Save(this);
        }

        void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            if (state == PlayerState.Stoped)
                btnPlay.IsChecked = false;
            else if (state == PlayerState.Paused)
                Resume();
            else
                Pause();
        }


        //播放
        public void Play(Music music)
        {
            if (player == null)
                player = new MediaPlayer();
            if (timer == null)
            {
                timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromSeconds(1);
                timer.Tick += timer_Tick;
            }
            timer.Start();
            player.Open(new Uri(music.Path));
            player.Play();
            pbMusicProcess.Maximum = music.Duration.TotalMilliseconds;
            //player.Position = TimeSpan.FromMinutes(3);
            state = PlayerState.Playing;
            btnPlay.IsChecked = true;
            tbMusicTitle.Text = music.Title;
            tbMusicArtist.Text = music.Artist;
        }

        public void Play(int index)
        {
            if (lvMusic.Items.Count == 0) return;
            if (index > lvMusic.Items.Count - 1)
                index = 0;
            else if (index < 0)
                index = lvMusic.Items.Count - 1;
            lvMusic.SelectedIndex = index;
        }

        //暂停
        public void Pause()
        {
            if (player != null)
                player.Pause();
            if (timer != null)
                timer.Stop();
            state = PlayerState.Paused;
            btnPlay.IsChecked = false;
        }

        //继续
        public void Resume()
        {
            if (player == null || timer == null)
            {
                state = PlayerState.Stoped;
                return;
            }
            timer.Start();
            player.Play();
            state = PlayerState.Playing;
            btnPlay.IsChecked = true;
        }

        //停止
        public void Stop()
        {
            state = PlayerState.Stoped;
            btnPlay.IsChecked = false;
        }

        //下一首
        public void Next(bool isActive = false)
        {
            int index = 0;
            switch (mode)
            {
                case LoopMode.ListCycle:
                    index = lvMusic.SelectedIndex + 1;
                    break;
                case LoopMode.SingleCycle:
                    if (isActive)
                        index = lvMusic.SelectedIndex + 1;
                    else
                        index = lvMusic.SelectedIndex;
                    break;
                case LoopMode.Random:
                    index = new Random(DateTime.Now.Millisecond).Next(0, lvMusic.Items.Count);
                    break;
            }
            Play(index);
        }

        //定时刷新进度条
        void timer_Tick(object sender, EventArgs e)
        {
            //pbMusicProcess.Maximum = player.NaturalDuration.TimeSpan.TotalMilliseconds;
            pbMusicProcess.Value = player.Position.TotalMilliseconds;

            Debug.WriteLine(pbMusicProcess.Maximum + " / " + pbMusicProcess.Value);
            if (Math.Abs(pbMusicProcess.Value - pbMusicProcess.Maximum) < 1) Next();
        }

        private void MusicItem_OnSelected(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("selected!");
            ListViewItem item = sender as ListViewItem;
            if (item == null) return;
            Music music = item.DataContext as Music;
            if (music == null) return;
            Play(music);
        }

        //双击播放音乐
        private void MusicItem_OnClick(object sender, MouseButtonEventArgs e)
        {
            ListViewItem item = sender as ListViewItem;
            if (item == null) return;
            TimeSpan nowTime = DateTime.Now.TimeOfDay;
            //第一次点击
            if (item.Tag == null)
            {
                item.Tag = nowTime;
                e.Handled = true;
                return;
            }
            //判断两次单击间隔
            TimeSpan oldTime = (TimeSpan)item.Tag;
            if ((nowTime - oldTime) > TimeSpan.FromMilliseconds(300))
                e.Handled = true;
            item.Tag = nowTime;
        }
    }
}
